﻿-- TRIGGERS

CREATE OR REPLACE FUNCTION system.register_sensor_name() RETURNS trigger AS $reg_sensor$
    DECLARE
	sensor_name_r system.sensor_name%ROWTYPE;
    BEGIN
	RAISE NOTICE 'Calling register_sensor_name(%)', NEW.id;
	SELECT * INTO sensor_name_r FROM system.sensor_name WHERE id=NEW.id;
	IF sensor_name_r.id IS NULL THEN
	    INSERT INTO system.sensor_name(id, is_active) VALUES(NEW.id, TRUE);
	END IF;
	RETURN NEW;
    END;
$reg_sensor$ LANGUAGE plpgsql
RETURNS NULL ON NULL INPUT;

DROP TRIGGER IF EXISTS register_sensor_name_trigg ON system.sensor CASCADE;

CREATE TRIGGER register_sensor_name_trigg
    AFTER INSERT ON system.sensor
    FOR EACH ROW
    EXECUTE PROCEDURE system.register_sensor_name();